def mergejoin(table_s, table_r, joinAttr):
    ts = table_s
    tr = table_r
    js = 0
    jr = 1
    
    if len(ts) < len(tr):
        ts = table_r
        tr = table_s
        js = 1
        jr = 0
    
    ps = 0
    pr = 0
    result = []
    
    while ps < len(ts):
        els = ts[ps]
        subset = [els]
        pr = 0
        done = False
        if  ps < len(ts)-1:
            while not done and ps < len(ts):
                    ps += 1
                    nels = ts[ps]
                    iguais = True
                    for j in joinAttr:
                        if not nels[j[js]] == els[j[js]]:
                            iguais = False
                            break
                    if iguais:
                        subset += [nels]
                    else:
                        done = True
        else:
            ps += 1
            
        elr = tr[pr]
        while pr < len(tr) - 1:
            iguais = True
            for j in joinAttr:
                if not els[j[js]] == elr[j[jr]]:
                    iguais = False
                    break
            if not iguais:
                pr += 1
                elr = tr[pr]
            else:
                break
        
        done = False
        while not done:
            iguais = True
            for j in joinAttr:
                if not els[j[js]] == elr[j[jr]]:
                    iguais = False
                    break
            if iguais:
                for temps in subset:
                    result += [(temps, elr)]
            if pr < len(tr) - 1:
                pr += 1
                elr = tr[pr]
            else:
                done = True
    
    return result


def custoMergeJoin():
    pass